#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "common.hpp"
namespace Inet
{

  class InetAdrr
  {
  private:
    // 将端口号由网络格式转为本地格式
    void PostNet2Host()
    {
      _port = ::ntohs(_net_addr.sin_port);
    }
    void IpNet2Host()
    {
      char buff[64];
      const char *ip = ::inet_ntop(AF_INET, CONV(&_net_addr.sin_addr), buff, sizeof(buff));
      (void)ip;
      _ip = buff;
    }

  public:
    InetAdrr()
    {}
    InetAdrr(const struct sockaddr_in &addr) : _net_addr(addr)
    {
      PostNet2Host();
      IpNet2Host();
    }
    InetAdrr(uint16_t port) : _port(port), _ip("")
    {
      _net_addr.sin_family = AF_INET;
      _net_addr.sin_addr.s_addr = INADDR_ANY;
      // 端口号传进来是本地格式 要转化
      _net_addr.sin_port = ::htons(_port);
    }
    std::string IP()
    {
      return _ip;
    }
    uint16_t Port()
    {
      return _port;
    }
    struct sockaddr *NetAddr() { return CONV(&_net_addr); }
    socklen_t NetAddrLen() { return sizeof(_net_addr); }
    ~InetAdrr()
    {
    }

  private:
    struct sockaddr_in _net_addr;
    std::string _ip;
    uint16_t _port;
  };
}